﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using ZLCMS.Business.TranferParam;
using ZLCMS.Web.SystemManage.Control;
using System.Collections.Generic;
using Newtonsoft.Json;
using NHibernate;
using DotNet.Common.TransferParam;
using NHibernate.Criterion;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Commands.User.Commands.ProductSku;
using DotNet.Common.Command;
using ZLCMS.Commands.User.Util;

namespace ZLCMS.Web.SystemManage.Basics.ProductSKU
{
    public partial class ProductAdd : System.Web.UI.Page
    {
        protected FrameHelper _framePage;
        public string _userAccount;
        protected ShopCategory _categoryDb;
        protected ShopProductInfo productDB;
        private IList<ShopSkuGroup> sku_groups;
        private List<ShopCategory> _list;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ控件
            _framePage = new FrameHelper(this);
            _userAccount = UserKit.GetUserAccountFailLogin();


            if (!AuthUtil.CheckAuthorization("PRODUCT_MAN", "ADD", _userAccount))
            {
                _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作失败-权限不足!" });
                return;
            }
            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                AddBussines();
            }
        }

        protected void InitializeGlobalValue()
        {

        }

        #region 初始化内容 -protected void InitializeContent()
        /// <summary>
        /// 初始化内容
        /// </summary>
        protected void InitializeContent()
        {
            fc_open.Config = new Business.UploadFileInfo.UploadConfig()
            {
                Thumbnail = new ThumbnailConfig()
                {
                    Mode = "HW",
                    Auto = true,
                    Name = "thumb",
                    Height = 250,
                    Width = 250
                },
                UploadDir = _userAccount + "/product/"
            };
            //页面控件值

            using (var session = SessionFactoryHelper.CreateSession())
            {
                _categoryDb = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", int.Parse(Request["cid"]))).UniqueResult<ShopCategory>();
                if (!IsPostBack)
                {
                    tb_end_time.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    //sku属性
                    ParamKit.Bind("ProductKind", ddl_product_kind, null, null, null, "shop", "shop");
                    rpt_tag.DataSource = session.CreateQuery("from ShopTagInfo where Status!='9' ").List<ShopTagInfo>();
                    rpt_tag.DataBind();

                    categoryName.Value = _categoryDb.CategoryName;
                    cid.Value = _categoryDb.Id.ToString();
                    rp_skugroup.DataSource = GetSkuGroups(session, _categoryDb);
                    rp_skugroup.DataBind();
                    //分类搜索属性
                    IList<ShopSearchPropertyGroup> list = new List<ShopSearchPropertyGroup>();

                    _list = new List<ShopCategory>();
                    GetParentsSearchProperty(_categoryDb.ParentId, session);

                    list = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.Eq("CategoryId", _categoryDb.Id)).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();

                    IList<ShopSearchPropertyGroup> currentCategorySPList = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.In("CategoryId", _list.Select(c => c.Id).ToList())).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();
                    foreach (ShopSearchPropertyGroup s in currentCategorySPList)
                    {
                        list.Add(s);
                    }
                    rpt_category_property.DataSource = list; 
                    rpt_category_property.DataBind();
                }
            }
        }
        #endregion

        #region 添加产品 +protected void AddBussines()
        /// <summary>
        /// 添加产品
        /// </summary>
        protected void AddBussines()
        {
            ICommandResult<EditProductResult> res = new EditProductCommand().Execute(new EditProductParameter()
                 {
                     Id = -1,
                     InteriorCode = tb_interior_code.Text,
                     ProductNo = "",
                     ProductName = tb_name.Text,
                     ShortDesc = tb_shortdesc.Text,
                     MarketPrice = decimal.Parse(tb_mprice.Text),
                     SalePrice = decimal.Parse(tb_sprice.Text),
                     TagIds = ecbk_user_tag.Checked ?ehid_tids.Value:  string.Empty ,
                     Score = int.Parse(tb_score.Text),
                     Coins = 0,
                     Storage = int.Parse(tb_storage.Text),
                     ThumbnailImg = fc_open.Value,
                     ProductImg = fc_relatedimgs.Value,
                     Kind = ddl_product_kind.SelectedValue,
                     IsForSale = "0",
                     IsCommend = "0",
                     IsHot = "0",
                     IsSpecialOffer = "0",
                     SellCount = "0",
                     IsLimitTime = cbx_is_limit.Checked ? "1" : "0",
                     EndTime = DateTime.Parse(tb_end_time.Text),
                     KindRuleId = int.Parse(string.IsNullOrEmpty(tb_rule_id.Text.Trim()) ? "0" : tb_rule_id.Text.Trim()),
                     IsVirtual = ddl_product_kind.SelectedValue == "shop" ? "0" : "1",
                     AddTime = DateTime.Now,
                     GroundingTime = DateTime.Now,
                     Hits = "0",
                     TypePrefix = _categoryDb.Prefix,
                     Description = txt_description.Value,
                     ParamContent = txtParamContent.Value,
                     OwnerAccount = _userAccount,
                     AvailableCoupon = ckb_available_coupon.Checked == true ? 1 : 0,
                     TypeId = int.Parse(cid.Value),
                     SkuGroup = Request.Form.GetValues("sku_group"),
                     PropertyItemValue = hid_property_item.Value
                 });
            if (res.Error)
            {
                _framePage.Alert(new ReturnCode()
                {
                    statusCode = 300,
                    message = "操作失败!该内部编码已存在."
                });
            }
            else
            {
                EditProductResult resData = res.Result;
                _framePage.Alert(new ReturnCode()
                   {
                       statusCode = 200,
                       message = "操作成功!",
                       callbackType = "forward",
                       forwardUrl = "/SystemManage/Basics/ProductSKU/ProductEdit.aspx?pid=" + resData.Product.Id
                   });
            }
        }
        #endregion

        #region 取得所有父节点 GetParents
        /// <summary>
        /// 取得所有父节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="session"></param>
        private List<ShopCategory> GetParents(int id, ISession session)
        {
            var list = new List<ShopCategory>();
            var parent = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", id)).UniqueResult<ShopCategory>();
            if (parent != null)
            {
                list.Add(parent);
                list.AddRange(GetParents(parent.ParentId, session));
            }
            return list;
        }
        #endregion

        #region 取得该分类的所有sku组 GetSkuGroups
        /// <summary>
        /// 取得该分类的所有sku组
        /// </summary>
        /// <param name="session"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        private IList<ShopSkuGroup> GetSkuGroups(ISession session, ShopCategory category)
        {
            var list = GetParents(category.ParentId, session);
            list.Add(category);
            var groups = session.CreateCriteria<ShopSkuGroup>().Add(Expression.In("CategoryId", list.Select(c => c.Id).ToList())).List<ShopSkuGroup>();
            return groups;
        }
        #endregion

        #region 绑定分类搜索属性列表
        /// <summary>
        /// 绑定分类搜索属性列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rpt_category_property_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate
            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("rpt_category_property_item") as Repeater;//找到里层的repeater对象
                ShopSearchPropertyGroup property = (ShopSearchPropertyGroup)e.Item.DataItem;//找到分类Repeater关联的数据项 
                using (var session = SessionFactoryHelper.CreateSession())
                {
                    rep.DataSource = session.CreateQuery("from ShopSearchPropertyItem where SearchPropertyId= :pid").SetParameter("pid", property.Id).List<ShopSearchPropertyItem>();
                    rep.DataBind();
                }
            }
        } 
        #endregion

        private void GetParentsSearchProperty(int id, ISession session)
        {
            var parent = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", id)).UniqueResult<ShopCategory>();
            if (parent != null)
            {
                _list.Add(parent);
                GetParentsSearchProperty(parent.ParentId, session);
            }
        }

        //#region 取得所有sku组 GetSkuGroups
        ///// <summary>
        ///// 取得所有sku组
        ///// </summary>
        ///// <param name="session"></param>
        ///// <param name="category"></param>
        ///// <returns></returns>
        ///// 
        //private IList<ShopSkuGroup> GetSkuGroups(ISession session, ShopProductInfo product)
        //{
        //    if (!string.IsNullOrEmpty(product.CustomField) && product.CustomField != "[]")
        //    {
        //        var CustomData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustomData>>(product.CustomField);
        //        if (CustomData != null)
        //            return CustomData.Select(c => c.Group).ToList();
        //    }
        //    return new List<ShopSkuGroup>(); ;
        //}
        //#endregion
  //#region 更新产品SKU字段
        //public void UpdateProductField(ISession session, List<SKUGroup> data, ShopProductInfo product)
        //{
        //    if (!string.IsNullOrEmpty(product.CustomField) && product.CustomField != "[]")
        //    {
        //        var CustomData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustomData>>(product.CustomField);
        //        if (CustomData != null)
        //        {
        //            foreach (var d in data)
        //            {
        //                bool on = false;
        //                foreach (var item in CustomData)
        //                {
        //                    if (item.Items.Where(i => i.Id == d.ItemId).Any())
        //                    {
        //                        on = true;
        //                    }
        //                }
        //                if (!on)
        //                {
        //                    CustomData.Where(c => c.Group.Id == d.GroupId).FirstOrDefault().Items.Add
        //                   (
        //                      session.Get<ShopSkuItem>(d.ItemId)
        //                   );
        //                }
        //            }
        //        }
        //        product.CustomField = Newtonsoft.Json.JsonConvert.SerializeObject(CustomData);
        //        session.Update(product);
        //        session.Flush();
        //    }
        //}
        //#endregion


        //#region 生成SKU产品
        ///// <summary>
        ///// 生成SKU产品
        ///// </summary>
        //private void SaveSkuProduct()
        //{
        //    using (var session = SessionFactoryHelper.CreateSession())
        //    {
        //        List<List<ShopSkuItem>> sku_items = new List<List<ShopSkuItem>>();

        //        var groups = GetSkuGroups(session, productDB);
        //        if (groups.Count > 0)
        //        {
        //            sku_groups = groups;
        //            foreach (var group in groups)
        //            {
        //                var group_items = new List<ShopSkuItem>();
        //                var skuitem = session.CreateCriteria<ShopSkuItem>().Add(Expression.Eq("SkuGroupId", group.Id)).List<ShopSkuItem>();
        //                group_items.AddRange(skuitem);
        //                sku_items.Add(group_items);
        //            }


        //            var skulist = session.CreateCriteria<ShopSkuProduct>().Add(Expression.Eq("ProductNo", productDB.ProductNo)).List<ShopSkuProduct>();
        //            var products = GenerateProducts(sku_items);
        //            foreach (var sku_product in products)
        //            {
        //                bool exists = false;
        //                foreach (var item in skulist)
        //                {
        //                    if (IsEquals(item, sku_product))
        //                    {
        //                        exists = true;
        //                    }
        //                }
        //                if (!exists)
        //                {
        //                    session.Save(sku_product);
        //                    session.Flush();
        //                    string no = sku_product.Id.ToString();
        //                    while (no.Length < 10)
        //                    {
        //                        no = "0" + no;
        //                    }
        //                    sku_product.ProductSkuCode = productDB.ProductNo + "_SKUNO" + no;
        //                    sku_product.IsShow = "1";
        //                    sku_product.Status = "1";
        //                    session.Save(sku_product);
        //                    session.Flush();
        //                    //
        //                    UpdateProductField(session, Newtonsoft.Json.JsonConvert.DeserializeObject<List<SKUGroup>>(sku_product.ParamCode), productDB);
        //                }
        //            }
        //        }
        //    }
        //} 
        //#endregion


        //#region 生成sku商品列表
        ///// <summary>
        ///// 生成sku商品列表
        ///// </summary>
        ///// <param name="sku_items"></param>
        ///// <returns></returns>
        //private List<ShopSkuProduct> GenerateProducts(List<List<ShopSkuItem>> sku_items)
        //{
        //    List<ShopSkuProduct> products = new List<ShopSkuProduct>();
        //    for (int i = 0; i < sku_items[0].Count; i++)
        //        NodeCompute(sku_items, 0, i, new Node() { Nodes = new List<Node>() }, products);
        //    return products;
        //} 
        //#endregion

        ///// <summary>
        ///// 节点计算
        ///// </summary>
        ///// <param name="sku_items"></param>
        ///// <param name="level"></param>
        ///// <param name="cloumn"></param>
        ///// <param name="parentNode"></param>
        ///// <param name="products"></param>
        //private void NodeCompute(List<List<ShopSkuItem>> sku_items, int level, int cloumn, Node parentNode, List<ShopSkuProduct> products)
        //{
        //    var node = new Node() { Nodes = new List<Node>(), Item = sku_items[level][cloumn] };
        //    parentNode.Nodes.Add(node);
        //    node.Parent = parentNode;
        //    level++;
        //    if (level < sku_items.Count)
        //    {
        //        int i = 0;
        //        foreach (var item in sku_items[level])
        //        {
        //            NodeCompute(sku_items, level, i, node, products);
        //            i++;
        //        }
        //    }
        //    else
        //    {
        //        products.Add(ComplateNode(node));
        //    }
        //}

        ///// <summary>
        ///// 使用node生成sku商品
        ///// </summary>
        ///// <param name="node"></param>
        ///// <returns></returns>
        //private ShopSkuProduct ComplateNode(Node node)
        //{
        //    string no = "";
        //    List<SKUGroup> groups = new List<SKUGroup>();
        //    foreach (var item in sku_groups)
        //    {
        //        groups.Add(new SKUGroup()
        //        {
        //            GroupName = item.SkuName,
        //            GroupId = item.Id
        //        });
        //    }
        //    while (node != null && node.Item != null)
        //    {
        //        var group = groups.Where(g => g.GroupId == node.Item.SkuGroupId).FirstOrDefault();
        //        no += group.GroupId + ":" + node.Item.Id + "-";
        //        group.ItemId = node.Item.Id;
        //        group.ItemName = node.Item.ItemName;
        //        node = node.Parent;
        //    }
        //    string param = Newtonsoft.Json.JsonConvert.SerializeObject(groups);


        //    var sku_product = new ShopSkuProduct()
        //    {
        //        ParamCode = param == null ? "" : param,
        //        ProductSkuCode = no.TrimEnd('-'),
        //        ProductSkuTitle = productDB.ProductName,
        //        MarketPrice = Convert.ToDecimal(tb_mprice.Text),
        //        SalePrice = Convert.ToDecimal(tb_sprice.Text),
        //        CreateDate = DateTime.Now,
        //        ProductNo = productDB.ProductNo,
        //        Status = "1",
        //        IsShow = "1",
        //        Storage = int.Parse(tb_storage.Text)
        //    };
        //    return sku_product;
        //}


        ///// <summary>
        ///// 比较两个产品的sku参数是否相同
        ///// </summary>
        ///// <param name="p1"></param>
        ///// <param name="p2"></param>
        ///// <returns></returns>
        //public bool IsEquals(ShopSkuProduct p1, ShopSkuProduct p2)
        //{
        //    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

        //    var d1 = js.Deserialize<List<SKUGroup>>(p1.ParamCode);
        //    var d2 = js.Deserialize<List<SKUGroup>>(p2.ParamCode);

        //    if (d1.Count != d2.Count)
        //        return false;

        //    for (int i = 0; i < d1.Count; i++)
        //    {
        //        var group = d2.Where(d => d.GroupId == d1[i].GroupId).FirstOrDefault();
        //        if (group == null)
        //            return false;
        //        else if (d1[i].ItemId != group.ItemId)
        //            return false;
        //    }
        //    return true;

        //}

    }
}
